package com.lanou.myim.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.lanou.myim.R;
import com.lanou.myim.adapter.DiscoveryFragmentAdapter;
import com.lanou.myim.entity.CommentEty;
import com.lanou.myim.entity.EventBusConstant;
import com.lanou.myim.entity.IdeaEty;
import com.lanou.myim.tools.ParseSingleton;
import com.lanou.myim.ui.activity.PersonalDataActivity;
import com.parse.ParseObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by dllo on 16/3/3.
 */
public class DiscoveryFragment extends BaseFragment implements ParseSingleton.Succeed, DiscoveryFragmentAdapter.Perspective {
    private ListView listView;
    private DiscoveryFragmentAdapter adapter;
    private List<ParseObject> list;
    private ImageView publish;
    private EditText editText;
    private EditText pictureEditText;
    private ImageView selectPicture;
    public final static int CONSULT_DOC_PICTURE = 200;
    public final static int CONSULT_BACKGROUND_PICTURE = 201;
    private String userName;
    private int SELECT_PICTURE = 0;
    private int SELECT_CAMERA = 1;
    private Bitmap bmp;
    private ImageView background;
    private ImageView userPicture;
    private TextView userNickName;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery, null);
        EventBus.getDefault().register(this);
        publish = (ImageView) view.findViewById(R.id.publish_discovery);
        listView = (ListView) view.findViewById(R.id.discovery_listView);
        View headListView = inflater.inflate(R.layout.discavery_headview, null);
        background = (ImageView) headListView.findViewById(R.id.backGround);
        userPicture = (ImageView) headListView.findViewById(R.id.discovery_personalPicture);
        userNickName = (TextView) headListView.findViewById(R.id.discovery_head_nickName);
        listView.addHeaderView(headListView);
        list = new ArrayList<>();
        userName = EMChatManager.getInstance().getCurrentUser();
        ParseSingleton.setBitmap(userName, userPicture);
        userNickName.setText(userName);
        ParseSingleton.setDescr(userName, userNickName);
        final String userName = EMChatManager.getInstance().getCurrentUser();
        ParseSingleton.gettingData(userName, list, this);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_orange_light, android.R.color.holo_orange_light);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        list = new ArrayList<ParseObject>();
                        Toast.makeText(getActivity(), "稍等", Toast.LENGTH_SHORT).show();
                        ParseSingleton.gettingData(userName, list, DiscoveryFragment.this);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final View view1 = factory.inflate(R.layout.editbox, null);
        editText = (EditText) view1.findViewById(R.id.publish_editText);
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
// TODO Auto-generated method stub
                CharSequence[] items = {"相册", "相机"};
                new AlertDialog.Builder(getActivity()).setTitle("选择图片来源").setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == SELECT_PICTURE) {
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/*");
                            intent.putExtra("crop", "true");
                            intent.putExtra("aspectX", 1.5);// 裁剪框比例
                            intent.putExtra("aspectY", 1);
                            intent.putExtra("outputX", 300);// 输出图片大小
                            intent.putExtra("outputY", 150);
                            intent.putExtra("return-data", true);
                            startActivityForResult(intent, CONSULT_BACKGROUND_PICTURE);
                        }
                    }
                }).create().show();
            }
        });
        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                CharSequence[] items = {"相册", "相机"};
                new AlertDialog.Builder(getActivity()).setTitle("选择图片来源").setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == SELECT_PICTURE) {
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/*");
                            intent.putExtra("crop", "true");
                            intent.putExtra("aspectX", 1);// 裁剪框比例
                            intent.putExtra("aspectY", 1);
                            intent.putExtra("outputX", 150);// 输出图片大小
                            intent.putExtra("outputY", 150);
                            intent.putExtra("return-data", true);
                            startActivityForResult(intent, CONSULT_DOC_PICTURE);
                        }
                    }
                }).create().show();
            }
        });
        publish.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //final String userName = EMChatManager.getInstance().getCurrentUser();
                builder.setTitle("发表看法").setView(view1).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ParseSingleton.publishIdea(userName, editText.getText().toString());
                    }
                }).setNegativeButton("取消", null).create().show();
                return false;
            }
        });
        return view;
    }


    @Override
    public void refreshPraise() {
        adapter.refresh();
    }

    @Override
    public void refreshComment() {
        adapter.refresh();
    }

    @Override
    public void ok(List<ParseObject> list) {
        ParseSingleton.setBitmap(userName, userPicture);
        ParseSingleton.setBackground(userName, background);
        userNickName.setText(userName);
        ParseSingleton.setDescr(userName, userNickName);
        if (list.size() > 0) {
            Log.d("DiscoveryFragment", "list.get(0):" + list.get(0).getString("userName"));
            adapter = new DiscoveryFragmentAdapter(getActivity(), list, this);
            listView.setAdapter(adapter);
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final View view2 = factory.inflate(R.layout.edit_picture_box, null);
        selectPicture = (ImageView) view2.findViewById(R.id.select_publish_picture);
        pictureEditText = (EditText) view2.findViewById(R.id.publish_picture_editText);
        final AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
        if (requestCode == CONSULT_DOC_PICTURE) {
            if (data == null) {
                return;
            }
            if (bmp != null) {
                bmp.recycle();
            }// 如果不释放的话，不断取图片，将会内存不够
            bmp = data.getParcelableExtra("data");
            selectPicture.setImageBitmap(bmp);
            builder1.setTitle("说点什么").setView(view2).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ParseSingleton.publishPicture(userName, pictureEditText.getText().toString(), bmp);
                }
            }).setNegativeButton("取消", null).create().show();

            //bmp = BitmapFactory.decodeFile(path);


        } else if (requestCode == CONSULT_BACKGROUND_PICTURE) {
            if (data == null) {
                return;
            }
            if (bmp != null) {
                bmp.recycle();
            }// 如果不释放的话，不断取图片，将会内存不够
            bmp = data.getParcelableExtra("data");
            ParseSingleton.publishBackgroundPicture(userName, bmp);
            background.setImageBitmap(bmp);


        } else {
            Toast.makeText(getActivity(), "请重新选择图片", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void comments(final String time, final int position) {
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final View view1 = factory.inflate(R.layout.editbox, null);
        editText = (EditText) view1.findViewById(R.id.publish_editText);
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("评论").setView(view1).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ParseSingleton.comment(time, userName, editText.getText().toString(), DiscoveryFragment.this,position);
            }
        }).setNegativeButton("取消", null).create().show();

    }

    @Override
    public void praise(String time,int position ) {
            ParseSingleton.praise(time, userName, DiscoveryFragment.this, position);
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(Integer i) {
        if (i == EventBusConstant.REFRESH_CIRCLE_OF_FRIENDS){
            ParseSingleton.gettingData(userName, list, DiscoveryFragment.this);
        }

    }

//    @Subscribe(threadMode = ThreadMode.MainThread)
//    public void onMainEvent(CommentEty commentEty) {
//        adapter.refresh();
//    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
